<template>
  <BasicDrawer ref="drawerRef" v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="1000px" destroyOnClose showFooter @ok="handleSubmit">
    <div :class="prefixCls">
      <Collapse v-model:activeKey="activeKey" :bordered="false" ghost>
        <CollapsePanel key="2" >
          <template #header>
            <span class="item-label">
              授权主体
            </span>
          </template>

          <div class="form-item" v-if="!state.subjectId">
            <FormListSelect 
              :maxHeight="300"
              selectType="selectRoleSubject"
              selectTitleSuffix="授权主体"
              @select="selectSubject"
            />
          </div>

          <div class="form-item" v-if="state.subjectId">
            <a-input v-model:value="selectSubjectInfo" readonly></a-input>
          </div>
        </CollapsePanel>

        <CollapsePanel key="3" >
          <template #header>
            <span class="item-label">
              权限策略
            </span>
          </template>

          <div class="form-item">
            <FormListSelect 
              :maxHeight="400"
              selectType="permPolicy"
              :selectList="initSelectPermPolicy"
              :queryParams="{ apiNamespaceCode: state.apiNamespaceCode }"
              selectTitleSuffix="权限策略"
              @select="selectPermPolicy"
            />
          </div>
        </CollapsePanel>
      </Collapse>
    </div>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, reactive, toRaw, computed, unref, useAttrs } from 'vue';
  import { CollapsePanel, Collapse } from "ant-design-vue"
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useDesign } from "/@/hooks/web/useDesign"
  import { FormListSelect } from "/@/components/My/ListSelect/index"
  import * as permPolicyApi from '/@/api/iam/permPolicy';
  import { BasicDrawer, useDrawer, useDrawerInner } from "/@/components/Drawer"
  import { subjectTypeMap, ConfigProp } from './data'

  const emit = defineEmits(["success", "register"])
  const { createMessage } = useMessage();
  const { prefixCls } = useDesign("authorize")
  const activeKey = ref('2');
  const fromValue = reactive<any>({});
  const selectSubjectInfo = ref()
  const initSelectPermPolicy = ref<any[]>()

  const state = ref({
    apiNamespaceCode: null,
    subjectType: null,
    subjectId: null,
    subjectName: null,
    config: {} as ConfigProp
  }) 

  const handleSetSubjectInfo = () => {
    const { subjectType, subjectId, subjectName } = state.value
    selectSubjectInfo.value =  `已选择${subjectTypeMap[subjectType].name}主体：` + `${subjectName}（${subjectId}）`
  }

  const selectPermPolicy = (v) => {
    console.log('==> selectPermPolicy', v)
    fromValue.policyIds = v.map(e => e.id)
  }

  const selectSubject = (v) => {
    console.log('==> selectSubject', v)
    fromValue.subjectIds = v.map(e => e.id)
  }
  
  const init = async () => {
    const { subjectType, subjectId, apiNamespaceCode } = state.value
    if (!subjectType) {
      return
    }
    subjectId && handleSetSubjectInfo()

    if (subjectId) {
      const resourceList = await permPolicyApi.listSubjectPermPolicy({ 
        subjectId, subjectType,
        apiNamespaceCode
      })
      const selectData = resourceList.map(e => ({
        name: e.policy.name,
        id: e.policy.id,
        remark: e.policy.remark,
      }))
      initSelectPermPolicy.value = selectData
      selectPermPolicy([ ...selectData ])
      selectSubject([ { id: subjectId} ])
      
    }
  }

  
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      console.log('data', data)
      state.value = { ...data }
      init()
    } finally {
      setDrawerProps({ loading: false })
    }
  })

  const getTitle = computed(() => '新增授权');

  const handleSubmit = async () => {
    setDrawerProps({ confirmLoading: false, loading: true })
    const { assignSubjectPermPolicyApi } = state.value.config || {}
    try {
      if (!assignSubjectPermPolicyApi) {
        console.error("保存主体权限策略失败, 未配置 assignSubjectPermPolicyApi 属性", state.value.config)
        createMessage.error("保存失败")
        return
      }

      await assignSubjectPermPolicyApi({ ...toRaw(fromValue) })
      emit('success')
      createMessage.success("授权成功")
      closeDrawer()
    } finally {
      setDrawerProps({ loading: false })
    }
  }

</script>

<style lang="less">
 @prefix-cls: ~"@{namespace}-authorize";

.@{prefix-cls} {
  padding: 5px;
 
  .ant-card-head {
    background-color: #F7F9FA !important;
  }

  .ant-select {
    width: 100% !important;
  }

  .item-label {
    box-sizing: border-box;
    width: 50px;
    padding-right: 10px;
    cursor: pointer;
  }
  .form-item {
    margin-left: 10px;
  }

  .collapse-header-desc {
    margin-left: 10px;
  }

  .no-collapse-form-item {
    display: flex;
    align-items: center;
    margin-left: 20px;
    width: 100%
  }
}
</style>